package util;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * 通用类
 * 
 * @author WangFei
 */
public class Func {

    private static final Log log = LogFactory.getLog(Func.class);

    /**
     * 判断字符串是否为空
     * 
     * @param str
     * @return
     */
    public static boolean checkNullOrEmpty(Object str) {

        if (str == null)
            return true;

        if (str.toString().trim().replace(" ", "").equals(""))
            return true;

        if (str.toString().trim().equalsIgnoreCase("null"))
            return true;

        if (str.toString().trim().toLowerCase().equals("undefined"))
            return true;

        return false;
    }

    /**
     * 删除文件
     * 
     * @param file
     * @return
     */
    public static boolean deleteFile(File file) {
        if (file == null)
            return false;

        if (!file.exists())
            return false;

        if (file.isDirectory())
            return false;

        return file.delete();
    }

    /**
     * 删除文件
     * 
     * @param filePath 文件路径
     * @return
     */
    public static boolean deleteFile(String filePath) {
        File file = new File(filePath);

        return deleteFile(file);
    }

    /**
     * 批量删除文件
     * 
     * @param fileList
     * @return
     */
    public static boolean deleteFile(List<String> fileList) {
        if (fileList == null)
            return false;

        int result = 0;
        for (String filePath : fileList) {
            if (deleteFile(filePath)) {
                result++;
            }
        }

        return result == fileList.size();
    }

    /**
     * 解析字符串
     * 
     * @param obj
     * @return
     */
    public static String parseStr(Object obj) {

        if (obj == null) {
            return "";
        }

        if (obj.toString().equalsIgnoreCase("null")
                || obj.toString().equalsIgnoreCase("undefined")) {
            return "";
        }

        return String.valueOf(obj);
    }

    /**
     * 解析整型
     * 
     * @param str
     * @return
     */
    public static int parseInt(String str) {

        int result = 0;
        if (checkNullOrEmpty(str)) {
            return result;
        }

        try {
            result = Integer.parseInt(str);
        }
        catch (Exception e) {
            e.printStackTrace();

            return result;
        }

        return result;
    }

    /**
     * 解析浮点型数据
     * 
     * @param str
     * @return
     */
    public static double parseDbl(String str) {
        if (checkNullOrEmpty(str))
            return 0;

        double result = 0.0;
        try {
            result = Double.parseDouble(str);
        }
        catch (Exception e) {
            e.printStackTrace();

        }

        return result;
    }

    /**
     * 解析浮点型
     * 
     * @param str
     * @return
     */
    public static float parseFloat(String str) {
        if (checkNullOrEmpty(str))
            return 0;

        float result = 0;

        try {
            result = Float.parseFloat(str);
        }
        catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 解析布尔型
     * 
     * @param obj
     * @return
     */
    public static boolean parseBoolean(Object obj) {

        boolean result = false;

        if (obj == null)
            return result;

        if (isNumber(obj.toString())) {
            return Func.parseInt(obj.toString()) > 0;
        }

        return Boolean.valueOf(obj.toString());

    }

    private static Pattern attachmentPattern = null;

    private static Pattern mathPattern = null;
    static {
        String mathReg = "^[-+]?[0-9]+(([Ee]?[-+]?[0-9]*)|([.]?[0-9]*[Ee]?[-+]?))[0-9]+$";
        mathPattern = Pattern.compile(mathReg);

        String attReg = "\\d*[;]{1,2}|\"(\\w*)?\"";
        attachmentPattern = Pattern.compile(attReg);
    }

    /**
     * 判断是否为数字
     * 
     * @param obj
     * @return
     */
    public static boolean isNumber(String obj) {

        if (checkNullOrEmpty(obj))
            return false;

        Matcher m = mathPattern.matcher(obj);

        return m.find();
    }

    // 根据Unicode编码完美的判断中文汉字和符号
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
            return true;
        }
        return false;
    }

    /**
     * 完整的判断中文汉字和符号
     * 
     * @param input
     * @return
     */
    public static boolean isChinese(String input) {
        char[] ch = input.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            char c = ch[i];
            if (isChinese(c)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 序列化PHPData
     * 
     * @param dataMap
     * @return
     */
    public static String serializeToPHPData(Map<String, String> dataMap) {
        StringBuffer sb = new StringBuffer();

        int size = dataMap.size();

        sb.append("a:" + size + ":{");

        for (Iterator<Entry<String, String>> it = dataMap.entrySet()
                .iterator(); it.hasNext();) {
            Entry<String, String> entry = it.next();

            String key = entry.getKey();
            String value = entry.getValue();

            // 添加key值
            sb.append("i:").append(key).append(";");

            // 获取字符串长度
            int length = 0;
            char[] chars = value.toCharArray();
            for (int i = 0; i < chars.length; i++) {
                char c = chars[i];
                if (isChinese(c)) {
                    length += 3;// PHP序列化话后PHP中文字符长度为3
                }
                else {
                    length += 1;
                }
            }

            // 添加value值
            sb.append("s:").append(length).append(":")
                    .append("\"" + value + "\"").append(";");
        }

        sb.append("}");

        return sb.toString();
    }

    /**
     * 反序列化php数据
     * 
     * @param org
     * @return
     */
    public static Map<String, String> unSerializeFromPHP(String org) {
        Map<String, String> rtnMap = new HashMap<String, String>();

        if (checkNullOrEmpty(org))
            return rtnMap;

        Matcher m = attachmentPattern.matcher(org);

        int i = 1;
        String k = "";
        String v = "";
        while (m.find()) {
            String value = m.group().replace("\"", "").replace(";", "");
            if (checkNullOrEmpty(value))
                continue;
            if ((i % 2) != 0) {// 奇数为KEY
                k = value;
            }
            else if ((i % 2) == 0) { // 偶数为VALUE
                v = value;
                rtnMap.put(k, v);
            }
            ++i;
        }

        return rtnMap;
    }

    /**
     * 创建唯一GUID
     * 
     * @return
     */
    public static String newGuid() {
        return UUID.randomUUID().toString();
    }

    /**
     * 远程调用zpapi_provider里的数据
     * 
     * @param urlStr
     * @return
     */
    public static String transToWeb(String urlStr) {
        log.info("----------------------------类Func,方法：transToWeb(),调用接口地址以及参数："
                + urlStr + "----------------------------------");

        String str = "";
        try {
            URL url = new URL(urlStr);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();// 远程调取zpapi系统里的数据，post提交，返回json格式的数据
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded;charset=UTF-8");
            conn.setRequestProperty("Accept-Language", "zh-cn");
            conn.setRequestProperty("Accept-Encoding", "gzip, deflate");
            InputStream input = conn.getInputStream();
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(input, "UTF-8"));
            str = in.readLine();
            in.close();
        }
        catch (Exception e) {
            e.printStackTrace();
            log.error("Func error: Exception:", e);
        }
        return str;
    }

}
